package com.cbgolf.oa.activity.result;

import static com.cbgolf.oa.util.AnimaUtil.stopLoading;

import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.support.v4.content.ContextCompat;
import android.support.v4.widget.SwipeRefreshLayout;
import android.view.View;
import android.widget.ListView;
import android.widget.TextView;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.cbgolf.oa.R;
import com.cbgolf.oa.adapter.ScoreHistoryAdapter;
import com.cbgolf.oa.base.BaseActivity;
import com.cbgolf.oa.entity.ScoreHistoryBean;
import com.cbgolf.oa.entity.ScoreHistoryDataBean;
import com.cbgolf.oa.net.NetCallBack;
import com.cbgolf.oa.net.NetUtils;
import com.cbgolf.oa.net.Web;
import com.cbgolf.oa.net.WebAPI;
import com.cbgolf.oa.util.AnimaUtil;
import com.cbgolf.oa.util.Util;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import org.xutils.view.annotation.ViewInject;
import org.xutils.x;

/**
 * @author lq
 * @author Created by lq on 2017/9/6.
 */

public class ScoreHistoryActivity extends BaseActivity implements
    SwipeRefreshLayout.OnRefreshListener {

  //top
  @ViewInject(R.id.topBack_ll)
  private View topBack;
  @ViewInject(R.id.title_tv)
  private TextView topTitle;
  //bady
  @ViewInject(R.id.a_coupon_history_refresh_layout)
  private SwipeRefreshLayout refreshLayout;
  @ViewInject(R.id.a_coupon_history_listview)
  private ListView listView;
  //error
  @ViewInject(R.id.g_error_ll)
  private View errorView;
  @ViewInject(R.id.g_error_tv)
  private TextView errorTv;
  @ViewInject(R.id.g_error_reload_tv)
  private TextView reLoadTv;
  @ViewInject(R.id.g_error_loading_tv)
  private TextView loadingTv;
  //var
  private List<ScoreHistoryBean> listData = new ArrayList<>();
  private boolean isLoading;
  Handler handler = new Handler();
  private ScoreHistoryAdapter adapter;

  @Override
  protected void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.a_coupon_history);
  }

  @Override
  protected void findViews() {
    x.view().inject(this);
  }

  @Override
  protected void setViews() {
    topTitle.setText("记分历史");
    adapter = new ScoreHistoryAdapter(context);
    listView.setAdapter(adapter);

    // 设置下拉圆圈上的颜色，蓝色、绿色、橙色、红色
    refreshLayout.setColorSchemeResources(R.color.bg_blue, R.color.text_gray,
        R.color.white, R.color.bg_blue);
//        refreshLayout.setColorSchemeResources(android.R.color.holo_blue_light,
//                android.R.color.holo_red_light, android.R.color.holo_orange_light, android.R.color.holo_green_light);
    refreshLayout.setDistanceToTriggerSync(300);// 设置手指在屏幕下拉多少距离会触发下拉刷新
    refreshLayout.setSize(SwipeRefreshLayout.LARGE);
    refreshLayout
        .setProgressBackgroundColorSchemeColor(ContextCompat.getColor(context, R.color.white));
//        refreshLayout.setPageCount(pageSize);
    refreshLayout.setEnabled(false);

  }

  @Override
  protected void setListener() {
    topBack.setOnClickListener(v -> finish());
    refreshLayout.setOnRefreshListener(this);
    reLoadTv.setOnClickListener(v -> getData());

  }

  @Override
  protected void loadData() {
    super.loadData();
    getData();
  }

  private void getData() {
    isLoading = true;
    if (!Util.isNetWorkConnected()) {
      showError(NONET);
      return;
    }
    String url = WebAPI.score_history_get;
    AnimaUtil.showLoading(context, loadingTv);
    Web.getOK(url, new NetCallBack(response -> {
      if (NetUtils.SUCCESS != response.statusCode) {
        showError(NETERROR);
        return;
      }
      if (Util.isNull(response.result)) {
        showError(NODATA);
        return;
      }

      Map<String, String> map = null;
      try {
        map = (Map<String, String>) JSON.parse(response.result);
      } catch (Exception e) {
        showError(NETERROR);
        return;
      }
      List<ScoreHistoryBean> list = new ArrayList<>();
      if (null != map && !map.isEmpty()) {
        ScoreHistoryBean m;
        try {
          JSONObject json = JSON.parseObject(response.result);
          for (String key : map.keySet()) {
            m = new ScoreHistoryBean();
            m.dateTime = key;
            List<ScoreHistoryDataBean> ls = JSON
                .parseArray(json.getString(key), ScoreHistoryDataBean.class);
            m.datas = ls;
            list.add(m);
          }
        } catch (Exception e) {
          e.printStackTrace();
        }
      }

      if (null != list && list.size() > 0) {
        showData();
        listData.clear();
        listData.addAll(list);
        adapter.setData(listData);
        adapter.upDataUI();
      } else {
        showError(NODATA);
      }
    }));
  }

  private void showData() {
    stopLoading();
    if (null != refreshLayout) {
      refreshLayout.setRefreshing(false);
    }
    isLoading = false;
    refreshLayout.setVisibility(View.VISIBLE);
    errorView.setVisibility(View.GONE);
  }

  private final int NONET = 1;
  private final int NETERROR = 2;
  private final int NODATA = 3;
  private final int LOADMORE = 4;


  private int page = 0;

  private void showError(int type) {
    stopLoading();
    if (null != refreshLayout) {
      refreshLayout.setRefreshing(false);
    }
    isLoading = false;
    if (type == LOADMORE && page > 0) {
      page--;
    }
    if (listData.size() > 0) {
      return;
    }
    refreshLayout.setVisibility(View.GONE);
    errorView.setVisibility(View.VISIBLE);
    reLoadTv.setVisibility(View.VISIBLE);
    switch (type) {
      case NONET:
        errorTv.setText(getResources().getString(R.string.no_net));
        break;
      case NETERROR:
        errorTv.setText(getResources().getString(R.string.net_error));
        break;
      case NODATA:
        errorTv.setText(getResources().getString(R.string.no_data));
        break;
      default:
        break;
    }


  }

  @Override
  public void onRefresh() {
    if (!isLoading) {
      handler.postDelayed(() -> getData(), 200);
    } else {
      refreshLayout.setRefreshing(false);
    }
  }

}

